// ALIBEGPS.cpp file
#include <Arduino.h>
#include <ALIBEGPS.h>
#include <SoftwareSerial.h>
#include <TinyGPS++.h>                 // Special version for 1.0

	SoftwareSerial _ss(ALIBE_GPS_DATA_PIN, ALIBE_GPS_UNUSED_PIN);
	TinyGPSPlus _agps;
			
	ALIBEGPS::ALIBEGPS(){
	//
	}
	
	//public
	void ALIBEGPS::begin(){
		_ss.begin(4800);
		//_initVars();
	}

	bool ALIBEGPS::getGPSData(){
		bool newdata = false;
		if (_feedGPS()){
			newdata = true;
			_gpsDumpToVars();
		}
		return newdata;
	}
	
	// private
	// Feed data to the _gps object for decoding as it becomes available 
	bool ALIBEGPS::_feedGPS() {
		while (_ss.available()) {
			if (_agps.encode(_ss.read())){
				return true;
			}
		}
		return false;
	}

	void ALIBEGPS::_gpsDumpToVars(){
		// Process GPS data and assign to internal vars.
		//
		// #of Satelllites
		gpsSatellites = _agps.satellites.value();
		
		// lat long
		gpsLat = _agps.location.lat();
		gpsLng = _agps.location.lng();
		
		//date time
		sprintf(gpsDate, "%02d/%02d/%04d", _agps.date.month(), _agps.date.day(), _agps.date.year());
		sprintf(gpsTime, "%02d.%02d.%02d", (_agps.time.hour() + (ALIBE_GPS_TIMEZONE_DIFF)), _agps.time.minute(), _agps.time.second());
		
		// Course and Heading
		gpsCourseDeg = _agps.course.deg();
		// Course and Heading
		if (gpsCourseDeg == 0) gpsHeading = "N";
        if (gpsCourseDeg== 90) gpsHeading= "E";
		if (gpsCourseDeg== 180) gpsHeading = "S";
  		if (gpsCourseDeg== 270) gpsHeading= "W";
		if (gpsCourseDeg== 360) gpsHeading= "N";
			
		if (gpsCourseDeg> 0 && gpsCourseDeg < 90) 	gpsHeading = "NE";
		if (gpsCourseDeg> 90 && gpsCourseDeg< 180) 	gpsHeading= "SE";
		if (gpsCourseDeg> 180 && gpsCourseDeg< 270) gpsHeading= "SW";
		if (gpsCourseDeg> 270 && gpsCourseDeg< 360)	gpsHeading= "NW";
			
		// Altitude
		gpsAlt= _agps.altitude.feet();
		//speed in mph
		gpsSpeed = _agps.speed.mph();
	}

	void ALIBEGPS::_initVars(){
		gpsHeading = "NA";
		gpsLat=0.0;
		gpsLng=0.0;
		sprintf(gpsDate,"");
		sprintf(gpsTime,"");
		gpsSpeed=0;
		gpsCourseDeg=0.0;
		gpsAlt=0;
		gpsSatellites=0;
		gpsSpeed=0;
	}
